import Blender
from Blender import Mesh, Scene, Window, sys, Image, Draw

def write(filename):
	if not filename.lower().endswith('.hmf'):
		filename += '.hmf'
	
	object= Blender.Object.GetSelected()[0]
	if not object:
		Blender.Draw.PupMenu('Error%t|Select 1 active object')
		return

	meshname = object.data.name
	me = Blender.Mesh.Get(meshname)          # get the selected mesh
	
	if not me:
		Blender.Draw.PupMenu('Error%t|Could not get mesh data from active object')
		return
		
	print 'HMF Export path: "%s"' % filename
	time1 = sys.time()

	#check to see if we are exporting triangles or quads
	quadcount = 0
	for f in me.faces:
		if len(f.v) == 4:
			f.sel = 1
			quadcount +=1
	
	#see if the faces are quads or triangles, or a mix
	#if they are trinangles or quads only, then we will export them
	#otherwise, convert the mesh to triangles first
	vertsPerFace = 3
	if quadcount > 0 and quadcount == len(me.faces):
		vertsPerFace = 4
	elif quadcount > 0 and quadcount != len(me.faces):
		metemp = me.__copy__()
		metemp.quadToTriangle(0) # more=0 shortest length
		me = metemp

	
	file = open(filename, "w")
	
	# Write Header
	file.write('# Blender v%s HMF File: %s\n' % (Blender.Get('version'), Blender.Get('filename').split('/')[-1].split('\\')[-1] ))
	file.write('HMF Helix Model Format\n')
	file.write('Major Version: 1\n')
	file.write('Minor Version: 0\n')
	file.write('Vertices Per Face: %d\n' % (vertsPerFace))
	file.write('Faces: %d\n' % (len(me.faces)))
	file.write('Vertices: %d\n' % (len(me.faces) * vertsPerFace))

	
	userBuffers = 1      #There is at least normal data

	if me.vertexColors:			#is there vertex color data?
		userBuffers += 1
	if me.faceUV:				#is there texture coordinate data?
		userBuffers += 1
	
	file.write('User-defined Buffers: %d\n\n' % (userBuffers))
	
	#write face data
	file.write('Start Face Data:\n')
	vertices = 0
	for f in me.faces:
		for v in f:
			file.write('%d ' % (vertices))
			vertices += 1
		file.write('\n')
	
	#write vertex data
	file.write('\nStart Vertex Data:\n')
	for f in me.faces:
		for v in f.verts:
			file.write('%f %f %f\n' % (v.co.x, v.co.y, v.co.z))

	#write normal data
	file.write('\nUser-defined Buffer: NORMAL_DATA\n')
	file.write('Parts Per Vertex: 3\n')
	for f in me.faces:
		for v in f.verts:
			if f.smooth:
				file.write('%f %f %f\n' % (v.no.x, v.no.y, v.no.z))
			else:
				file.write('%f %f %f\n' % (f.no.x, f.no.y, f.no.z))

	#if there is any texture coordinate data, write it out
	if me.faceUV:
		file.write('\nUser-defined Buffer: TEXTURE_COORDINATE_DATA\n')
		file.write('Parts Per Vertex: 2\n')
		for f in me.faces:
			for uv in f.uv:
				file.write('%f %f\n' % (uv.x, uv.y))
	
	#if there is any texture coordinate data, write it out
	if me.vertexColors:
		file.write('\nUser-defined Buffer: VERTEX_COLOR_DATA\n')
		file.write('Parts Per Vertex: 3\n')
		for f in me.faces:
			for col in f.col:
				file.write('%f %f %f\n' % (float(col.r)/255.0, float(col.g)/255.0,float(col.b)/255.0))	

	file.close()
	print "HMF Export time: %.2f" % (sys.time() - time1)


if __name__ == '__main__':
	Window.FileSelector(write, 'Export Helix Model Format HMF', sys.makename(ext='.hmf'))